﻿using System;
using System.Configuration;

using WebImageResizer.Properties;
using WebImageResizer.Utils;

namespace WebImageResizer
{
	/// <summary>
	/// 	Generic factory class for creating IImageStore, IImageTool and IImageProvider
	/// </summary>
	public class Factory
	{
		#region Readonly & Static Fields

		private static IImageProvider s_ImageProvider;
		private static IImageStore s_ImageStore;
		private static IImageTool s_ImageTool;
		private static readonly object s_SyncLock = new object();

		#endregion

		#region Class Methods

		public static IImageProvider GetImageProvider()
		{
			if (s_ImageProvider.IsNull())
			{
				lock (s_SyncLock)
				{
					if (s_ImageProvider.IsNull())
					{
						Type imageProviderType = Type.GetType(Settings.Default.ImageProviderType);
						if (imageProviderType.IsNull())
						{
							throw new ConfigurationErrorsException(string.Format("Unable to resolve image provider type: {0}",
								Settings.Default.ImageProviderType));
						}

						s_ImageProvider = Activator.CreateInstance(imageProviderType) as IImageProvider;
					}
				}
			}

			return s_ImageProvider;
		}

		public static IImageStore GetImageStore()
		{
			if (s_ImageStore.IsNull())
			{
				lock (s_SyncLock)
				{
					if (s_ImageStore.IsNull())
					{
						Type imageStoreType = Type.GetType(Settings.Default.ImageStoreType);
						if (imageStoreType.IsNull())
						{
							throw new ConfigurationErrorsException(string.Format("Unable to resolve image store type: {0}",
								Settings.Default.ImageStoreType));
						}

						s_ImageStore = Activator.CreateInstance(imageStoreType) as IImageStore;
					}
				}
			}

			return s_ImageStore;
		}

		public static IImageTool GetImageTool()
		{
			if (s_ImageTool.IsNull())
			{
				lock (s_SyncLock)
				{
					if (s_ImageTool.IsNull())
					{
						Type imageToolType = Type.GetType(Settings.Default.ImageToolType);
						if (imageToolType.IsNull())
						{
							throw new ConfigurationErrorsException(string.Format("Unable to resolve image tool type: {0}",
								Settings.Default.ImageToolType));
						}

						s_ImageTool = Activator.CreateInstance(imageToolType) as IImageTool;
					}
				}
			}

			return s_ImageTool;
		}

		#endregion
	}
}